<?php
declare (strict_types = 1);

namespace uctoo\middleware;

use uctoo\util\exception\TokenException;
use think\exception\HttpResponseException;
use think\Response;

class H5PaltAuth
{
    /**
     * 处理请求
     *
     * @param \think\Request $request
     * @param \Closure       $next
     * @return Response
     */
    public function handle($request, \Closure $next)
    {
        $auth = \uctoo\util\library\H5PlatAuth::instance();
        $auth->setAccessToken($request->header('authorization',null));
        $request->auth = $auth;
        try{
            $user = $request->auth->checkUser();
        }catch (TokenException $e){
            $result = [
                'code' => $e->getCode(),
                'msg'  => $e->getMessage(),
                'time' => $request->server('REQUEST_TIME'),
                'data' => null,
            ];
            return Response::create($result, 'json', 200);
        }
        $request->user = $user;
        return $next($request);
    }
}
